package com.io.predicates;

import lombok.Data;
import org.springframework.cloud.gateway.handler.predicate.AbstractRoutePredicateFactory;
import org.springframework.stereotype.Component;
import org.springframework.util.StringUtils;
import org.springframework.web.server.ServerWebExchange;

import java.util.Arrays;
import java.util.List;
import java.util.function.Predicate;

/**
 * The class/interface 自定义路由断言工厂
 * 1、在配置文件中，添加一个Age的断言配置
 * 2、自定义一个断言工厂, 实现断言方
 *
 * @author guodd
 * @version 1.0 use jdk 1.8
 */
@Component
public class AgeRoutePredicateFactory extends AbstractRoutePredicateFactory<AgeRoutePredicateFactory.Config> {

    // 构造器
    public AgeRoutePredicateFactory() {
        super(AgeRoutePredicateFactory.Config.class);
    }

    // 读取配置文件，将值赋值到配置类的属性上
    @Override
    public List<String> shortcutFieldOrder() {
        // 这文件是有顺序
        return Arrays.asList("minAge", "maxAge");
    }

    // 断言逻辑
    @Override
    public Predicate<ServerWebExchange> apply(AgeRoutePredicateFactory.Config config) {
        return serverWebExchange -> {
            // 接受前台参数值
            String age = serverWebExchange.getRequest().getQueryParams().getFirst("age");
            if (!StringUtils.isEmpty(age)) {
                int ageInt = Integer.parseInt(age);
                return ageInt < config.getMaxAge() && ageInt > config.getMinAge();
            }
            return false;
        };
    }

    @Data
    public static class Config {
        /**
         * 属性描述：最小年龄
         */
        private Integer minAge;

        /**
         * 属性描述：最大年龄
         */
        private Integer maxAge;
    }
}